package com.gitee.apanlh.util.net.http.handler;

import com.gitee.apanlh.exp.HttpConfigException;
import com.gitee.apanlh.exp.HttpException;
import com.gitee.apanlh.util.net.http.BaseHttpConfigure;
import com.gitee.apanlh.util.net.http.HttpClient;
import com.gitee.apanlh.util.net.http.HttpConfig;
import com.gitee.apanlh.util.net.http.HttpRequest;
import com.gitee.apanlh.util.net.http.handler.body.cast.HttpRequestBodyCast;
import com.gitee.apanlh.web.http.HttpMethod;

import java.net.HttpURLConnection;

/**
 * 	HTTP配置拦截器，装配实现对HTTP连接配置处理
 * 	
 * 	@author Pan
 */
public class HttpConnectionConfigureChain implements HttpRequestInterceptor, BaseHttpConfigure {
	
	@Override
	public HttpRequest chain(HttpRequest httpRequest, HttpClient httpClient, HttpRequestBodyCast bodyCast, HttpInterceptorChain chain) throws HttpException {
		return chain.proceed(configure(httpRequest, httpClient), httpClient);
	}
	
	@Override
	public HttpRequest configure(HttpRequest httpRequest, HttpClient httpClient) throws HttpConfigException {
		//	获取配置
		HttpConfig config = httpRequest.getConfig();
		HttpURLConnection client = httpClient.getClient();
		try {
			client.setRequestMethod(HttpMethod.getRequestMethodName(config.getHttpMethod()));
			
			client.setConnectTimeout(config.getConnectTimeout());
			client.setReadTimeout(config.getReadTimeout());
			
			client.setDoOutput(config.hasHasOutput());
			client.setDoInput(config.hasHasInput());
			
			//	JDK1.8默认复用连接
			client.setRequestProperty("Connection", "keep-alive");
			return httpRequest;
		} catch (Exception e) {
			throw new HttpConfigException(e.getMessage(), e);
		}
	}
}
